/**
 * Constructor. Loads libraries, gets container elements, inits data structures.
 */
poll = function() {
    google.load("visualization", "1", {packages:["columnchart"]});
    this.prefs_ = new gadgets.Prefs();
    this.pollContainer_ = document.getElementById('poll');
    this.votes_ = [];
    this.myVotes_ = [];
    this.poll_ = {
        'title': 'Would you?',
        'id': 1,
        'owner': 116162715910880940331, 
        'options': [
            {'title': 'Yes',
                'votes': [
                    {'name': 'Greg'},
                    {'name': 'Zach'}]},
            {'title':'No',
                'votes': []},
            {'title':'Maybe',
                'votes': [
                    {'name': 'Pooch'}]}]};
};

poll.prototype.inWave = function() {
    return wave && wave.isInWaveContainer();
};

poll.prototype.hasVoted = function() {

};

poll.prototype.getVote = function() {
    var voteButtons = document.pollForm.voteGroup
    var vote = null;
    for (var i=0, voteButton; voteButton = voteButtons[i]; i++) {
        if (voteButton.checked) {
            vote = i;
            break;
        }
    }
    return vote;
};

poll.prototype.castVote = function() {
    if (this.hasVoted()) {

    } else {
        debugger;
        var vote = this.getVote();
        if (typeof(vote) == 'number') {
            var myVote = {
                'pollId': this.poll_.id,
                'vote': vote,
                'voterId': this.viewer_.getId()
            };
            this.votes_[vote].push(myVote);
            this.myVotes_.push(myVote);

            this.renderPollGraph(this.poll_, this.votes_);


            var votesJson = gadgets.json.stringify(this.myVotes_);
            var req = opensocial.newDataRequest();
            req.add(req.newUpdatePersonAppDataRequest(opensocial.IdSpec.PersonId.VIEWER, 'votes', votesJson), "set_data");
            req.send(function(response) {
                if (response.get("set_data").hadError()) {
                    alert('Failed to save your vote');
                } else {
                    // Voted OK.
                }
            });
        }
    }
};

poll.prototype.loadPoll = function(callback) {
    var idOwnerFriends = opensocial.newIdSpec({
        'userId' : opensocial.IdSpec.PersonId.OWNER,
        'groupId' : opensocial.IdSpec.GroupId.FRIENDS });
    var idOwnerSelf = opensocial.newIdSpec({
        'userId' : opensocial.IdSpec.PersonId.OWNER,
        'groupId' : opensocial.IdSpec.GroupId.SELF });
    var params = {};
    params[opensocial.DataRequest.DataRequestFields.ESCAPE_TYPE] = opensocial.EscapeType.NONE;
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonAppDataRequest(idOwnerFriends, 'polls', params), 'pollsData');
    req.add(req.newFetchPersonAppDataRequest(idOwnerFriends, 'votes', params), 'votesData');
    req.add(req.newFetchPersonAppDataRequest(idOwnerSelf, 'votes', params), 'myVotesData');
    req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer_');
    req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.OWNER), 'owner_');
    req.send(callback);
};

poll.prototype.renderVoteButton = function(buttonText) {
    var voteButton = _dce('input');
    voteButton.type = 'button';
    voteButton.value = buttonText;
    voteButton.onclick = bind(this.castVote, this);
    this.pollContainer_.appendChild(voteButton);
};

poll.prototype.countVotesForPoll = function(allUserVoteData, poll) {
    var votes = [];
    for (var i=0; i<poll.options.length; i++) {
        votes[i] = [];
    }
    for (userVoteData in allUserVoteData) {
        if(userVoteData.votes) {
            debugger;
            for (var j=0, userVote; userVote = userVoteData.votes[j]; j++) {
                if (userVote.pollId = poll.id) {
                    votes[userVote.vote].push(userVote);
                }
            }
        }
    }
    return votes;
};

poll.prototype.render = function() {
    google.setOnLoadCallback(bind(function() {
        this.loadPoll(bind(function(response) {
            if (response.getErrorMessage()) {
                alert('Failed to load poll data');
            } else {
                debugger;
                this.viewer_ = response.get('viewer_').getData();
                var allVotes = response.get('votesData').getData();
                this.myVotes_ = response.get('myVotesData').getData()[this.viewer_.getId()].votes || [];
                var allPolls = response.get('pollsData').getData();
                for (var i=0, friendPolls; friendPolls = allPolls[i]; i++) {
                    if (friendPolls.poll) {
                        // Just get the first poll which a friend has for now.
                        this.poll_ = gadgets.json.pase(friendPolls.poll);
                        break;
                    }
                }
                this.votes_ = this.countVotesForPoll(allVotes, this.poll_, this.viewer_.getId());
                this.renderQuestion(this.poll_);
                this.renderVoteButton('Vote');
                this.renderPollGraph(this.poll_, this.votes_);
                gadgets.window.adjustHeight();
            }
        }, this));
    }, this));
};

poll.prototype.renderQuestion = function(poll) {
    var pollString = '<h1>' + poll.title + '</h1>' +
                     '<form id="pollForm" name="pollForm" action="">';
    for (var i=0, option; option = this.poll_.options[i]; i++) {
        pollString += '<input type="radio" name="voteGroup" id="option' + i + '"/>' +
                      '<label for="option' + i + '">' + option.title + '</label>';
    }
    
    pollString += '</form>';

    this.pollContainer_.innerHTML = pollString;

    
};

poll.prototype.renderPollGraph = function(poll, votes) {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Poll Title');
    data.addColumn('number', '# of votes');
    data.addRows(this.poll_.options.length);
    for (var i = 0, option; option = poll.options[i]; i++) {
        data.setValue(i, 0, option.title);
        data.setValue(i, 1, votes[i].length);
    }

    var graphContainer = document.getElementById('graph');
    graphContainer.innerHTML = '';
    var chart = new google.visualization.ColumnChart(graphContainer);
    chart.draw(data, {width: 400, height: 240, is3D: true, title: this.poll_.title, legend: 'none'});
};

gadgets.util.registerOnLoadHandler(function() {
    var p = new poll();
    p.render();
});